package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.core.NeueduException;
import com.neuedu.entity.UmsAdmin;
import com.neuedu.entity.UmsStudent;
import com.neuedu.mapper.UmsAdminMapper;
import com.neuedu.service.UmsAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.util.JwtUtil;
import com.neuedu.util.SystemUser;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author wangyu
 * @since 2025-09-02
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource(name = "hjredistemplate")
    RedisTemplate<String, Object> redisTemplate;
    @Override
    public Map<String, Object> login(String username, String password) {
        UmsAdmin umsAdmin = loginGetAdmin(username, password);
        String token = saveAndGetToken(umsAdmin);
        return Map.of("admin", umsAdmin, "token", token);
    }
    private UmsAdmin loginGetAdmin(String username, String password) {
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", username)
                .or().eq("email", username);
        UmsAdmin umsAdmin = this.getOne(wrapper);
        if (null == umsAdmin || !passwordEncoder.matches(password, umsAdmin.getPassword())) {
            throw new NeueduException("用户名或密码错误");
        }
        if (!umsAdmin.getActive()) {
            throw new NeueduException("该管理员已经禁用，无法登录");
        }
        return umsAdmin;
    }
    private String saveAndGetToken(UmsAdmin umsAdmin) {
        redisTemplate.opsForValue().set("teacher::" + umsAdmin.getId(), umsAdmin, 90, TimeUnit.MINUTES);
        return JwtUtil.create(new SystemUser(umsAdmin.getId(), "", "teacher"));
    }
}
